package com.itheima.Demo;

import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class Demo3 {
        private InputStream is;
        private SqlSession sqlSession;



    @Before
    public void init()throws Exception{
       //加载核心配置文件
         is = Resources.getResourceAsStream("MybatisConfig.xml");
        //获取sqlsession工厂对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //通过Ssqlsession工厂对象获取Sqlsession对象
         sqlSession = factory.openSession();
        //执行配置文件中的sql语句，并返回结果
        //处理结果
    }

    //释放资源
        @After
    public void destroy()throws Exception{
        sqlSession.commit();
        sqlSession.close();
        is.close();
        }


        @Test
    public void findAll(){
            List<User> users = sqlSession.selectList("UserMapper.findAll");
            for (User u : users) {
                System.out.println(u);
            }
        }

    @Test
    public void findById(){
        User u = sqlSession.selectOne("UserMapper.findById", 21);
        System.out.println(u);
    }



    @Test
    public void findCount(){
        int count = sqlSession.selectOne("UserMapper.findCount");
        System.out.println(count);
    }


    @Test
    public void findByName(){
        List<User> users = sqlSession.selectList("UserMapper.findByName", "李");
        for (User u : users) {
            System.out.println(u);
        }
    }

    @Test
    public void findByName2(){
        List<User> users = sqlSession.selectList("UserMapper.findByName2", "李");
        for (User u : users) {
            System.out.println(u);
        }
    }


    @Test
    public void saveReturnId(){
        User u=new User();
        u.setName("刘瑾");
        u.setGender("56");
        System.out.println("before:"+u);
        sqlSession.insert("UserMapper.saveReturnId",u);
        System.out.println("later:"+u);
    }

    @Test
    public void saveReturnId2(){
        User u=new User();
        u.setName("热");
        u.setGender("23");
        System.out.println("before:"+u);
        sqlSession.insert("UserMapper.saveReturnId2",u);
        System.out.println("later:"+u);
    }



}
